package com.enjoy.adv.client;

import com.enjoy.adv.vo.MessageType;
import com.enjoy.adv.vo.MyHeader;
import com.enjoy.adv.vo.MyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by HP on 2019/7/18.
 */
public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {
    private static final Log LOG = LogFactory.getLog(LoginAuthReqHandler.class);

    /*完成了三次握手后，发起登录请求*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(buildLoginReq());
    }

    //如果是握手应答的消息，需要判断是否认证成功
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MyMessage message= (MyMessage) msg;

        if (message.getMyHeader()!=null
               &&message.getMyHeader().getType()==MessageType.LOGIN_RESP.getValue() ){
            byte loginResult = (byte) message.getBody();
            if (loginResult!=(byte)0){
                //握手失败，关闭连接
                ctx.close();
            }else {
                LOG.info("Login is ok:"+message);
                ctx.fireChannelRead(msg);
            }
        }else {
            ctx.fireChannelRead(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }

    private MyMessage buildLoginReq(){
        MyMessage message=new MyMessage();
        MyHeader myHeader=new MyHeader();
        myHeader.setType(MessageType.LOGIN_REQ.getValue());
        message.setMyHeader(myHeader);
        return  message;
    }



}
